import Vue from 'vue'
import VueRouter from 'vue-router'
import { getItem } from '@/utils/storage'
import { getToken } from '@/api/user.js'
import store from '@/store'
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    component: () => import('@/views/layout'),
    children: [
      {
        path: '',
        component: () => import('@/views/home')
      },
      {
        path: '/video',
        component: () => import('@/views/video')
      },
      {
        path: '/qa',
        component: () => import('@/views/qa')
      },
      {
        path: '/my',
        component: () => import('@/views/my')
      }
    ]
  },
  {
    path: '/user',
    component: () => import('@/views/user')
  },
  {
    path: '/login',
    component: () => import('@/views/login')
  },
  {
    path: '/arctcle/:id',
    props: true, // 开启路由props传递id
    component: () => import('@/views/arctcle')
  },
  {
    path: '/search',
    component: () => import('@/views/search')
  }
]

const router = new VueRouter({
  routes
})

// 约定过期时间戳
const tokenTimeOut = 1 * 20 * 1000
// 前置路由守卫
router.beforeEach(async (to, from, next) => {
  // 获取登录时间戳
  const logindate = getItem('TOKENDTE')
  // 获取当前时间戳
  const currentDate = Date.now()
  if ((currentDate - logindate) > tokenTimeOut) {
    const res = await getToken()
    store.commit('lintUser', {
      ...store.state.user,
      token: res.data.data.token
    })
  }
  next()
})
export default router
